namespace ClassyBlog.Infrastructure
{
    using System;
    using System.Web.Mvc;

    public class CurrentBlog : IMvcFilter, IActionFilter
    {
        public CurrentBlog(ICurrentBlogProvider provider)
        {
            if (provider == null)
            {
                throw new ArgumentNullException("provider");
            }

            Provider = provider;
        }

        public int Order { get; set; }

        public bool AllowMultiple
        {
            get { return false; }
        }

        protected ICurrentBlogProvider Provider { get; private set; }

        public void OnActionExecuting(ActionExecutingContext filterContext)
        {
            if (filterContext == null)
            {
                throw new ArgumentNullException("filterContext");
            }

            SetBlog(filterContext.Controller);
        }

        public void OnActionExecuted(ActionExecutedContext filterContext)
        {
            if (filterContext == null)
            {
                throw new ArgumentNullException("filterContext");
            }

            SetBlog(filterContext.Controller.ViewData.Model);
        }

        protected virtual void SetBlog(object target)
        {
            var awared = target as ICurrentBlogAware;

            if ((awared != null) && (awared.Blog == null))
            {
                awared.SetBlog(Provider.Current);
            }
        }
    }
}